<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>角色授权</span>
      </div>

      <!-- 用户和角色选择 -->
      <el-form :inline="true" style="margin-top: 20px;">
        <el-form-item label="选择用户">
          <el-select v-model="selectedUser" filterable placeholder="请选择用户" style="width: 250px;" @change="loadUserRoles">
            <el-option
              v-for="user in filteredUsers"
              :key="user.id"
              :label="user.userName"
              :value="user.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择角色">
          <el-select v-model="selectedRole" placeholder="请选择角色" style="width: 250px;">
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.roleName"
              :value="role.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 授予权限按钮 -->
      <el-button type="primary" @click="grantRole" :disabled="!selectedUser || !selectedRole" style="margin-top: 20px;">授予权限</el-button>

      <!-- 权限列表条件渲染 -->
      <el-table :data="userRoles" style="width: 100%; margin-top: 20px;" v-if="selectedUser">
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="userName" label="用户名称"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="mini" type="danger" @click="revokeRole(scope.row.roleId,scope.row.userId)">撤销权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <p v-else style="margin-top: 20px;">请先选择一个用户。</p>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { fetchRoles, fetchUsers, fetchUserRoles, grantUserRole, revokeUserRole } from '@/api/sys/role';

export default defineComponent({
  setup() {
    const state = reactive({
      searchForm: {
        query: ''
      },
      selectedUser: null as number | null,
      selectedRole: null as number | null,
      users: [] as any[],
      roles: [] as any[],
      userRoles: [] as any[],
    });

    const filteredUsers = computed(() => {
      if (!state.searchForm.query) return state.users;
      return state.users.filter(user =>
        user.userName.toLowerCase().includes(state.searchForm.query.toLowerCase())
      );
    });

    const handleSearch = () => {
      // Search logic is handled by the computed property `filteredUsers`
    };

    const loadRoles = async () => {
      try {
        state.roles = await fetchRoles();
      } catch (error) {
        console.error('Error loading roles:', error);
      }
    };

    const loadUsers = async () => {
      try {
        state.users = await fetchUsers();
      } catch (error) {
        console.error('Error loading users:', error);
      }
    };

    const loadUserRoles = async (userId?: number) => {
      if (!userId) return;
      try {
        const roles = await fetchUserRoles({ userId });
        state.userRoles = roles.map(role => ({...role, id: `${userId}-${role.id}`})); // 确保每个角色ID是唯一的
      } catch (error) {
        console.error('Error loading user roles:', error);
      }
    };

    const grantRole = async () => {
      if (!state.selectedUser || !state.selectedRole) return;
      try {
        let res = await grantUserRole({ userId: state.selectedUser, roleId: state.selectedRole });
        ElMessage.success('角色授权成功！');
        await loadUserRoles(state.selectedUser);
      } catch (error) {
        debugger;
        ElMessage.error(error);
        console.error('Error granting role:', error);
      }
    };

    const revokeRole = async (roleId: number,userId: number) => {
      // const [userId, role] = roleId.split('-').map(Number);
      try {
        await revokeUserRole({userId:userId,roleId: roleId});
        ElMessage.success('角色撤销成功！');
        await loadUserRoles(userId);
      } catch (error) {
        ElMessage.error('角色撤销失败，请重试。');
        console.error('Error revoking role:', error);
      }
    };

    watch(() => state.selectedUser, async (newVal) => {
      if (newVal) {
        await loadUserRoles(newVal);
      }
    });

    const init = async () => {
      await Promise.all([loadRoles(), loadUsers()]);
    };

    init();

    return {
      ...toRefs(state),
      filteredUsers,
      handleSearch,
      grantRole,
      revokeRole,
    };
  }
});
</script>

<style scoped>
.box-card {
  width: 100%;
}
</style>